package com.photoeditor.demo.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.ui.widget.ripple.RippleTextView;
import com.common.base.utils.DeviceUtils;
import com.common.commercialize.utils.TaskRunnable;
import com.photoeditor.R;
import com.photoeditor.demo.app.ActionConstant;
import com.photoeditor.demo.app.AppApplication;
import com.photoeditor.demo.app.Global;
import com.photoeditor.demo.app.XActivity;
import com.photoeditor.demo.app.XFragment;
import com.photoeditor.demo.model.bean.BitmapBean;
import com.photoeditor.demo.model.bean.DateBean;
import com.photoeditor.demo.model.bean.SeparatorBean;
import com.photoeditor.demo.model.bean.ThumbnailBean;
import com.photoeditor.demo.model.event.FacePrivacyPolicyEvent;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.statistics.NotifyStoreUpdateStatisticUtil;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.adapter.gallery.FolderListAdapter;
import com.photoeditor.demo.ui.adapter.gallery.GalleryFragmentPageAdapter;
import com.photoeditor.demo.ui.adapter.gallery.ICheckedChangeListener;
import com.photoeditor.demo.ui.adapter.gallery.IFaceDetectListener;
import com.photoeditor.demo.ui.adapter.gallery.IOnFragmentChange;
import com.photoeditor.demo.ui.adapter.gallery.ListGridAdapter;
import com.photoeditor.demo.ui.fragement.HomeFragment;
import com.photoeditor.demo.ui.fragement.gallery.FaceGalleryFragment;
import com.photoeditor.demo.ui.fragement.gallery.GalleryFragment;
import com.photoeditor.demo.ui.fragement.gallery.OtherGalleryFragment;
import com.photoeditor.demo.ui.widget.CenterAlignImageSpan;
import com.photoeditor.demo.ui.widget.ScrollLimitViewPager;
import com.photoeditor.demo.ui.widget.gallery.GalleryRowItem;
import com.photoeditor.demo.util.AndroidDevice;
import com.photoeditor.demo.util.FileUtil;
import com.photoeditor.demo.util.FontUtil;
import com.photoeditor.demo.util.MediaTypeUtil;
import com.photoeditor.demo.util.PermissionUtil;
import com.photoeditor.demo.util.ShowBigImageUtils;
import com.photoeditor.demo.util.ToastUtil;
import com.photoeditor.demo.util.gallery.common.LoadThumbnailUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FALBUMQUIT;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FALBUMSHOW;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_NFALBUMQUIT;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_NFALBUMSHOW;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_KEY_FACE_FUN;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_KEY_NFEDITENTER;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_AGING;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_EDIT;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_FILTER;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_GENDER;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_PAST;
import static com.photoeditor.demo.util.DataConstant.IMAGE_DATA;

public class GalleryActivity extends XActivity implements IFaceDetectListener {

    public static final int REQUEST_CODE_PREVIEW = 101;

    public static final int REQUEST_CODE_MODIFY_PASSWORD = 102;

    public static final int REQUEST_CODE_RESET_PASSWORD = 103;

    public static final int REQUEST_CODE_BACKUP = 104;

    public static final int REQUEST_CODE_RECOVERY = 105;

    public static final int REQUEST_CODE_COLLAGE = 106;

    public static final int REQUEST_CODE_PICK_TO_EDIT = 107;

    public static final int REQUEST_CODE_TEMPLATE = 108;

    public static final int REQUEST_CODE_TAKEPHOTO = 109;

//    public static final String EXTRA_BACKUP_PATH = "extra_backup_path";
//
//    public static final String EXTRA_RECOVERY_PATH = "extra_recovery_path";
//
//    public static final String EXTRA_IS_FROM_CONFIRM_PWD_ACTIVITY = "extra_from_confirm_pwd_activity";

    //
    public static final String TYPE = "type";

    public static final String WITH_DATA = "with_data";

    public static final String DATA = "data";

    public static final String SP_REJECT_CAMERA_PERMISSION = "sp_reject_camera_permission";
    public static final int PERMISSION_CAMERA_CODE = 0x1000;

    private int mType = TYPE_FRAGMENT_GALLERY;

    public static final int TYPE_FRAGMENT_FACE = 0;
    public static final int TYPE_FRAGMENT_GALLERY = 0;
    public static final int TYPE_FRAGMENT_OTHER_GALLERY = 1;

    public static final String EXTRA_ENTRANCE = "entrance";
//    public static final String ENTRANCE_NORMAL = "normal";
//    public static final String ENTRANCE_SHORTCUT = "shortcut";
//    public static final String ENTRANCE_WIDGET = "widget";

    public int mSelectImgTotalNum = 15;
    public int mSelectVideoTotalNum = 4;

    private ScrollLimitViewPager mViewPager;

    private GalleryFragmentPageAdapter mPageAdapter;

    private ArrayList<XFragment> mFragments;

    /**
     * 返回按钮
     */
    private ImageView mBackBt;

    /**
     * Title
     */
    private TextView mTitle;

    public static String TODAY_KEY = ComponentContext.getContext().getString(R.string.today);
    public static String YESTERDAY_KEY = ComponentContext.getContext().getString(R.string.yesterday);
    public static String MONTH_KEY = ComponentContext.getContext().getString(R.string.this_month);
    public static String SPONSORED = "sponsored";
    public static String AD = "ad";

    private String mToday = TODAY_KEY;
    private String mYesterday = YESTERDAY_KEY;
    private String mMonth = MONTH_KEY;

    private View mTopPanel;
    private ImageView mPhotoBt;

    private View mSelectBanner;

    private View mCheckedTopPanel;
    private ImageView mCancelBt;
    private View mNumLayout;
    private boolean mNumLayoutChecked = false;
    private TextView mNumTv;
    private ImageView mSuperscript;
    private ImageView mShareBt;
    private ImageView mDeleteBt;

    //	private View mAlbumLayout;
    private TextView mFace;
    private TextView mAlbumTv;
    //	private View mPrivateLayout;

    private TextView mOtherTv;

    private int mSelectColor;
    private int mUnSelectColor;

    private View mLineLayout;
    private View mGalleryLine;
//	private View mPrivateLine;

    //设置密码然后移入私密箱
    private boolean mSettingAndMoveIn;
    private ArrayList<ThumbnailBean> mCheckedList;

    public static final String ACTION_REFRESH_GALLERY = "action_refresh_gallery";


    /**
     * 支持Intent 修改
     */
    private int mIntentMode = INTENT_ACTION_NONE;
    private String mMimeType = null;
    private String mEntrance;
    /**
     * 是否进入艺术滤镜
     */
    private boolean mIsEnterArtistFilter = false;

    public static final int INTENT_ACTION_NONE = 0;
    public static final int INTENT_ACTION_PICK = 1;
    public static final int INTENT_ACTION_GET_CONTENT = 2;
    public static final int INTENT_ACTION_PICK_TO_EDIT_AND_SHARE = 3;
    public static final int INTENT_ACTION_PICK_TO_COLLAGE = 4;
    public static final int INTENT_ACTION_CHANGE_TO_COLLAGE = 5;
    //这种模式是选择图片和所有的动态图片
    public static final int INTENT_ACTION_PICK_TO_EDIT = 6;
    public static final int INTENT_ACTION_PICK_TO_EDIT_AND_PUBLISH = 7;
    public static final int INTENT_ACTION_PICK_SCREEN_LOCK_BG = 8;
    public static final int INTENT_ACTION_PICK_TO_ADD_STICKER = 9;
    public static final int INTENT_ACTION_PICK_TO_BEAUTY_EDIT = 11;
    public static final int INTENT_ACTION_PICK_TO_APPLY_FILTER = 12;
    public static final int INTENT_ACTION_PICK_TO_TEMPLATE = 13;
    public static final int INTENT_ACTION_PICK_TO_FREESTYLE = 14;
    public static final int INTENT_ACTION_ADD_FOR_FREESTYLE = 15;
    public static final int INTENT_ACTION_CHANGE_TO_FREESTYLE = 16;
    public static final int INTENT_ACTION_PICK_TO_BEAUTY_OR_BODY_FUNTION_EDIT = 17;

    private String mStickerPkgName;
    private String mGifTitle;
    private int mAutoScrollPosition = -1;

    private String mFilerCategoryId;
    private String mFilterPkgName;

    private String mBackgroundCategoryName;
    private String mBackgroundItemName;

    private String mTemplatePkgName;
    private int mTemplateSupportImgNum;

    private MyOnPageChangeListener mPageListenr;

    /**
     * 分享处理
     */
    private int mCheckedVideoNum = 0;
    private int mCheckedAllNum = 0;


//    private ProgressDialog mShareDialog;
//
//    private ProgressDialog mProgressDialog;
//
//    private AlertDialog mBackUpDialog;
//
//    private AlertDialog mRecoveryDialog;

    //拼接相关部分
    private ArrayList<BitmapBean> mCollageBitmapBeans;
    private LinearLayout mSelectLayout;
    private View mLineBottom;
    private HorizontalScrollView mScrollView;
    private LinearLayout mScrollLayout;
    private TextView mSelectTip;
    private RippleTextView mNext;
    private RippleTextView mBtnDeleteAll;
    private LottieAnimationView mLoadingView;
    private RelativeLayout mCoverView;

    private RelativeLayout mContent;
    private boolean mSupportGifForFreestyle = true;

    private ContentObserver mMediaChangeObserver;
    private boolean mIsNeedExitPageAd = true;
    private String statisticsStr = "";

    //从主页btn点击进来
    private String mMainButtonEntrance;
    private boolean mReqPermissionFromSetting = false;

//    public static String photoPath = null;


    private ArrayList<BitmapBean> mImageList;

    public static void startGallerySelectEditImages(Context context) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_EDIT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        context.startActivity(intent);
    }

    public static void startGallerySelectEditImagesToBeauty(Context context) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_BEAUTY_EDIT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        context.startActivity(intent);
    }

    public static void startGallerySelectCollageImages(Context context) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_SELECT_IMAGES_TO_COLLAGE);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        context.startActivity(intent);
    }

    public static void startGallerySelectEditImages(Context context, String mainBtnEntrance) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_EDIT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        intent.putExtra(EXTRA_ENTRANCE, "main_page_editor_floating");
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainBtnEntrance);
        context.startActivity(intent);
    }

    public static void startGallerySelectEditImagesForArtist(Context context, String mainBtnEntrance, boolean isArtist) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_EDIT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        intent.putExtra(EXTRA_ENTRANCE, "main_page_editor_banner");
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainBtnEntrance);
        intent.putExtra(HomeFragment.EXTRA_IS_ARTIST, isArtist);
        context.startActivity(intent);
    }

    public static void startGallerySelectEditImagesForSticker(Context context, String mainBtnEntrance) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_ADD_STICKER_EDIT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        intent.putExtra(EXTRA_ENTRANCE, "main_page_editor_banner");
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainBtnEntrance);
        context.startActivity(intent);
    }

    public static void startGallerySelectEditImagesToBeauty(Context context, String mainBtnEntrance) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_BEAUTY_EDIT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainBtnEntrance);
        context.startActivity(intent);
    }

    public static void startGallerySelectCollageImages(Context context, String mainBtnEntrance) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_SELECT_IMAGES_TO_COLLAGE);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainBtnEntrance);
        context.startActivity(intent);
    }

    public static void startGallerySelectFreestyleImages(Context context, String mainBtnEntrance) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_SELECT_IMAGES_TO_FREESTYLE);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainBtnEntrance);
        context.startActivity(intent);
    }

    public static void startGallerySelectImageToApplyFilter(Context context, String categoryId, String pkgName) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_APPLY_FILTER);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.putExtra(ActionConstant.Extras.EXTRA_CATEGORY_ID, categoryId);
        intent.putExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME, pkgName);
        intent.putExtra(EXTRA_ENTRANCE, "main_page_editor_filter");
        intent.setType("image/*");
        context.startActivity(intent);
        SPDataManager.setFunctionEntrance(StatisticsConstant.MAIN_BTN_EDIT);
    }

    //gifTitle 应用gif时才添加
    public static void startGallerySelectImageToAddSticker(Context context, String pkgName, String gifTitle){
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_ADD_STICKER_EDIT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.putExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME, pkgName);
        intent.putExtra(ActionConstant.Extras.EXTRA_GIF_TITLE, gifTitle);
        intent.setType("image/*");
        context.startActivity(intent);
        SPDataManager.setFunctionEntrance(StatisticsConstant.MAIN_BTN_EDIT);
    }

    public static void startGallerySelectImageToAutoAddSticker(Context context, String pkgName, String gifTitle, int position) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_ADD_STICKER_EDIT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.putExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME, pkgName);
        intent.putExtra(ActionConstant.Extras.EXTRA_GIF_TITLE, gifTitle);
        intent.putExtra(ActionConstant.Extras.EXTRA_AUTO_SCROLL_POSITION, position);
        intent.setType("image/*");
        context.startActivity(intent);
        SPDataManager.setFunctionEntrance(StatisticsConstant.MAIN_BTN_EDIT);
    }

    public static void startGalleryChangeCollageImages(Activity context, int requestCode) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_CHANGE_IMAGES_TO_COLLAGE);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        context.startActivityForResult(intent, requestCode);
        SPDataManager.setFunctionEntrance(StatisticsConstant.MAIN_BTN_EDIT);
    }

    public static void startGalleryChangeFreestyleImages(Activity context, int requestCode, boolean supportGif) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_CHANGE_IMAGES_TO_FREESTYLE);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        intent.putExtra(ActionConstant.Extras.EXTRA_SUPPORT_GIF, supportGif);
        context.startActivityForResult(intent, requestCode);
        SPDataManager.setFunctionEntrance(StatisticsConstant.MAIN_BTN_FREESTYLE);
    }

    public static void startGalleryForGetContent(Activity context, int requestCode) {
        Intent intent = new Intent(android.content.Intent.ACTION_GET_CONTENT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.setType("image/*");
        context.startActivityForResult(intent, requestCode);
        SPDataManager.setFunctionEntrance(StatisticsConstant.MAIN_BTN_FREESTYLE);
    }

    /**
     * 跳转到BeautyOrBody的某个功能
     *
     * @param type 功能类型
     */
    public static void startGallerySelectImageToBeautyOrBodyFuntion(Context context, String type) {
        Intent intent = new Intent(ActionConstant.Actions.ACTION_PICK_TO_BEAUTY_OR_BODY_FUNTION_EDIT);
        intent.setComponent(new ComponentName(context, GalleryActivity.class));
        intent.putExtra(ActionConstant.Extras.EXTRA_BEAUTY_FUNTION_TYPE, type);
        intent.setType("image/*");
        context.startActivity(intent);
    }

    private IOnFragmentChange mFragmentChangeListener = new IOnFragmentChange() {

        @Override
        public void onFragmentCreated(int type) {
            if (type == mType) {
                showFragment(mType);
            }
        }

        @Override
        public void onDataChange(int type) {
            if (type == TYPE_FRAGMENT_OTHER_GALLERY) {
                OtherGalleryFragment ogf = ((OtherGalleryFragment) mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY));
                if (ogf.getMode() == OtherGalleryFragment.MODE_GALLERY) {
                    ogf.setSelectionNeedRefresh(true);
                } else {
                    ogf.setNeedRefresh(true);
                }
            } else {
                mFragments.get(type).setNeedRefresh(true);
            }
        }
    };


    private ICheckedChangeListener mListener = new ICheckedChangeListener() {

        @Override
        public void onCheckedStatusChange(boolean b) {
            if (b) {
                mTopPanel.setVisibility(View.INVISIBLE);
                mCheckedTopPanel.setVisibility(View.VISIBLE);
            } else {
                mTopPanel.setVisibility(View.VISIBLE);
                mCheckedTopPanel.setVisibility(View.GONE);
            }
        }

        @Override
        public void onVideoCheckedChange(boolean ischecked, int videoNum) {
            mCheckedVideoNum = videoNum;
        }

        @Override
        public void onCheckedNumChange(boolean hasVideoChecked, int num) {
            mCheckedAllNum = num;
            mNumTv.setText(num + "/" + mFragments.get(mType).getImageNum());
            if (mType == TYPE_FRAGMENT_FACE && (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face"))) {
                if (num == 0) {
                    mShareBt.setAlpha(0.6f);
                    mShareBt.setEnabled(false);
                    mDeleteBt.setAlpha(0.6f);
                    mDeleteBt.setEnabled(false);
                    ListGridAdapter adapter = mFragments.get(mType).getAdapter();
                    if (adapter != null) {
                        doCancel(adapter);
                    }
                } else {
                    mShareBt.setAlpha(1.0f);
                    mDeleteBt.setAlpha(1f);
                    mShareBt.setEnabled(true);
                    mDeleteBt.setEnabled(true);
                }
            } else if (mType == TYPE_FRAGMENT_GALLERY) {
                if (num == 0) {
                    mShareBt.setAlpha(0.6f);
                    mShareBt.setEnabled(false);
                    mDeleteBt.setAlpha(0.6f);
                    mDeleteBt.setEnabled(false);
                    ListGridAdapter adapter = mFragments.get(mType).getAdapter();
                    if (adapter != null) {
                        doCancel(adapter);
                    }
                } else {
                    mShareBt.setAlpha(1.0f);
                    mDeleteBt.setAlpha(1f);
                    mShareBt.setEnabled(true);
                    mDeleteBt.setEnabled(true);
                }
            } else if (mType == TYPE_FRAGMENT_OTHER_GALLERY) {
                OtherGalleryFragment ogf = (OtherGalleryFragment) mFragments.get(mType);
                if (ogf.getMode() == OtherGalleryFragment.MODE_GALLERY) {
                    if (num == 0) {
                        mShareBt.setAlpha(0.6f);
                        mShareBt.setEnabled(false);
                        mDeleteBt.setAlpha(0.6f);
                        mDeleteBt.setEnabled(false);
                        ogf.doCancel();
                    } else {
                        mShareBt.setAlpha(1.0f);
                        mDeleteBt.setAlpha(1f);
                        mShareBt.setEnabled(true);
                        mDeleteBt.setEnabled(true);
                    }
                } else {
                    if (num == 0) {
                        mDeleteBt.setAlpha(0.6f);
                        mDeleteBt.setEnabled(false);
                        ogf.doCancel();
                    } else {
                        mDeleteBt.setAlpha(1f);
                        mDeleteBt.setEnabled(true);
                    }
                }
            }
        }

        @Override
        public void onAllCheckedChange(boolean ischecked) {
            mNumLayoutChecked = ischecked;
        }
    };


    protected void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(mMediaChangeObserver);
        try {
            LoadThumbnailUtil.getInstance().recycle();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);
        setContentView(R.layout.activity_gallery);
        ButterKnife.bind(this);
        initIntentInfo();
        initView();
        initLockBackgrounds();

        if (mAutoScrollPosition != -1) {
            Toast.makeText(this, "Choose your photo to add this", Toast.LENGTH_SHORT).show();
        }

        EventBus.getDefault().register(this);

        /*boolean showGuideAgain = SPDataManager.isShowVideoCollageGuideAgain();
        SPDataManager.setShowVideoCollageGuideAgain(false);
        if (isPickToCollageMode() && (!SPDataManager.hasUseCollage() || showGuideAgain)) {
            SPDataManager.setHasUseCollage(true);
            *//*mGuideVideoDialog = new GuideDialog(this, R.string.guide_collage_title,
                    R.string.guide_collage_content,
                    R.string.got_it,
                    R.drawable.guide_collage, PreLoadConfig.CONFIG_GUIDE_COLLAGE_VIDEO_ID,
                    null);
            mGuideVideoDialog.show();*//*
        } else if (isPickToEditMode() && SPDataManager.isShowGifGuideAgain()) {
            //gif下载下来再展示
            PreloadManager preloadManager = PreloadManager.getInstance();
            String url = preloadManager.getConfig(PreLoadConfig.CONFIG_GUIDE_GIF_STICKER_ID);
            if (!TextUtils.isEmpty(url)) {
                String preloadFile = preloadManager.getPreloadFile(url);
                if (!TextUtils.isEmpty(preloadFile)) {
                    mGuideVideoDialog = new GuideDialog(this, R.string.guide_gif_sticker_title,
                            R.string.guide_gif_sticker_content,
                            R.string.try_it,
                            preloadFile,
                            null);
                    mGuideVideoDialog.show();
                    SPDataManager.setHasUseGifSticker(true);
                    SPDataManager.setCanShowGifSticker(false);
                    PreloadManager.getInstance().addIgnorePreloadUrl(url);
                }
            }
            SPDataManager.setShowGifGuideAgain(false);
        }*/
//        handlePermission();//选择了不再询问时，activity使用下面请求权限
        if (PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            StatisticsUtils.statisicsCustomFunction(StatisticsConstant.PERMISSION_GALLERY,
                    StatisticsConstant.PERMISSION_GALLERY_KEY_STORAGE_SHOW, String.valueOf(true));
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PermissionUtil.PERMISSION_REQ_CODE);
        }

    }

    private void initLockBackgrounds() {
        if (isPickScreenLockBg()) {
            final ArrayList<Uri> uris = getIntent().getParcelableArrayListExtra(ActionConstant.Extras.EXTRA_URI_ARRAY);
            if (uris != null && uris.size() > 0) {
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        for (Uri uri : uris) {
                            final BitmapBean bean = ImageHelper.getInterBitmapBeanFormUri(ComponentContext.getContext(), uri);
                            if (bean != null) {
//                                GalleryActivity.this.runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        addCollageBitmap(new ThumbnailBean(bean.mPath, bean.mDate, true,
//                                                bean.mUri, bean.mDegree, bean.mType), false, mType, null);
//                                    }
//                                });
                            }
                        }
                    }
                }.start();
            }
        }
    }

    /**
     * 获取数据时需要传入的参数
     * 0 -- all
     * 1 -- image + gif
     * 2 -- video
     * 3 -- image + 动态图片
     * 4 -- image
     *
     * @return
     */
    public String getParams() {
        String param = "4";
        /*if(isPickMode()){
            if (isPickToPipEditMode()) {
                param = "1";
            } else if (isChangeToCollageMode()){
                param = "4";
            } else if(isChangeToFreestyleMode() || isAddImage4Freestyle()) {
                if(mSupportGifForFreestyle) {
                    param = "1";
                } else {
                    param = "4";
                }
            } else if(isPickToEditMode() || isPickToEditAndPublishMode()){//如果是4.3以下的手机 则不显示图片
                if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2){
                    param = "1";
                } else {
                    param = "3";
                }
            } else if (isPickToBeautyEditMode()){
                param = "1";
            } else if(isPickToCollageMode()){
                param = "0";
            } else if(isPickToFreeStyle()){
                param = "1";
            } else if (isPickToCollageMode4Template()) {
                param = "1";
            } else if (isPickToBeautyFuntionEditMode()) {
                param = "1";
            } else {
                String type = getDataType();
                if (!TextUtils.isEmpty(type)) {
                    if (type.equalsIgnoreCase("image/*") || MediaFile.isImageFileType(MediaFile.getFileTypeForMimeType(type))) {
                        param = "1";
                    } else if (type.equalsIgnoreCase("video/*") || MediaFile.isVideoFileType(MediaFile.getFileTypeForMimeType(type))) {
                        param = "2";
                    }
                }
            }
        }*/
        return param;
    }

    public String getDataType() {
        return mMimeType;
    }

    public int getIntentType() {
        return mIntentMode;
    }

    /**
     * 是不是选择图片返回的模式 isPickToEditMode也包含在内
     *
     * @return
     */
    public boolean isPickMode() {
        return (mIntentMode == INTENT_ACTION_GET_CONTENT ||
                mIntentMode == INTENT_ACTION_PICK || mIntentMode == INTENT_ACTION_PICK_TO_EDIT_AND_SHARE
                || mIntentMode == INTENT_ACTION_PICK_TO_COLLAGE
                || mIntentMode == INTENT_ACTION_PICK_TO_FREESTYLE
                || mIntentMode == INTENT_ACTION_CHANGE_TO_COLLAGE
                || mIntentMode == INTENT_ACTION_PICK_TO_EDIT
                || mIntentMode == INTENT_ACTION_PICK_TO_EDIT_AND_PUBLISH
                || mIntentMode == INTENT_ACTION_PICK_SCREEN_LOCK_BG
                || mIntentMode == INTENT_ACTION_PICK_TO_ADD_STICKER
                || mIntentMode == INTENT_ACTION_PICK_TO_APPLY_FILTER
                || mIntentMode == INTENT_ACTION_PICK_TO_BEAUTY_EDIT
                || mIntentMode == INTENT_ACTION_PICK_TO_TEMPLATE
                || mIntentMode == INTENT_ACTION_ADD_FOR_FREESTYLE
                || mIntentMode == INTENT_ACTION_CHANGE_TO_FREESTYLE
                || mIntentMode == INTENT_ACTION_PICK_TO_BEAUTY_OR_BODY_FUNTION_EDIT);
    }

    /**
     * 是不是选择图片返回到编辑的并分享的模式
     *
     * @return
     */
    public boolean isPickToEditModeAndShare() {
        return mIntentMode == INTENT_ACTION_PICK_TO_EDIT_AND_SHARE;
    }

    /**
     * 是不是选择图片返回到编辑的模式
     *
     * @return
     */
    public boolean isPickToEditMode() {//这种模式是选择图片和所有的动态图片
        return mIntentMode == INTENT_ACTION_PICK_TO_EDIT;
    }

    /**
     * 是不是选择图片到美颜编辑的模式
     *
     * @return
     */
    public boolean isPickToBeautyEditMode() {
        return mIntentMode == INTENT_ACTION_PICK_TO_BEAUTY_EDIT;
    }

    /**
     * 是不是选择图片到美颜具体功能的模式
     *
     * @return
     */
    public boolean isPickToBeautyFuntionEditMode() {
        return mIntentMode == INTENT_ACTION_PICK_TO_BEAUTY_OR_BODY_FUNTION_EDIT;
    }

    /**
     * 是不是选择图片返回到编辑并发布的模式
     *
     * @return
     */
    public boolean isPickToEditAndPublishMode() {//这种模式是选择图片和所有的动态图片
        return mIntentMode == INTENT_ACTION_PICK_TO_EDIT_AND_PUBLISH;
    }

    /**
     * 是不是选择图片拼接的模式
     *
     * @return
     */
    public boolean isPickToCollageMode() {
        return mIntentMode == INTENT_ACTION_PICK_TO_COLLAGE;
    }

    public boolean isPickToFreeStyle() {
        return mIntentMode == INTENT_ACTION_PICK_TO_FREESTYLE;
    }

    public boolean isPickToCollageMode4Template() {
        return mIntentMode == INTENT_ACTION_PICK_TO_TEMPLATE;
    }

    public boolean isAddImage4Freestyle() {
        return mIntentMode == INTENT_ACTION_ADD_FOR_FREESTYLE;
    }


    public boolean isChangeToCollageMode() {
        return mIntentMode == INTENT_ACTION_CHANGE_TO_COLLAGE;
    }

    public boolean isChangeToFreestyleMode() {
        return mIntentMode == INTENT_ACTION_CHANGE_TO_FREESTYLE;
    }


    /**
     * 是不是选择锁屏图片
     *
     * @return
     */
    public boolean isPickScreenLockBg() {
        return mIntentMode == INTENT_ACTION_PICK_SCREEN_LOCK_BG;
    }

    /**
     * 是不是
     *
     * @return
     */
    public boolean isPickToAddSticker() {
        return mIntentMode == INTENT_ACTION_PICK_TO_ADD_STICKER;
    }

    public boolean isPickToApplyFilter() {
        return mIntentMode == INTENT_ACTION_PICK_TO_APPLY_FILTER;
    }

    public int getType() {
        return mType;
    }

    public void setNeedExitPageAd(boolean isNeedExitPageAd) {
        this.mIsNeedExitPageAd = isNeedExitPageAd;
    }

    /**
     * 初始化Intent的信息
     */
    private void initIntentInfo() {
        Intent i = getIntent();
        String action = i.getAction();
        mIsEnterArtistFilter = i.getBooleanExtra(HomeFragment.EXTRA_IS_ARTIST, false);
        if (Intent.ACTION_GET_CONTENT.equals(action)) {
            mIntentMode = INTENT_ACTION_GET_CONTENT;
            mMimeType = i.getType();
            String type = getParams();
        } else if (Intent.ACTION_PICK.equals(action)) {
            mIntentMode = INTENT_ACTION_PICK;
            mMimeType = i.getType();
            String type = getParams();
        } else if (ActionConstant.Actions.ACTION_IMAGE_PICK_TO_EDIT_AND_SHARE.equals(action)) {
            mIntentMode = INTENT_ACTION_PICK_TO_EDIT_AND_SHARE;
            mMimeType = i.getType();
            String type = getParams();
        } else if (ActionConstant.Actions.ACTION_SELECT_IMAGES_TO_TEMPLATE.equals(action)) {
            mIntentMode = INTENT_ACTION_PICK_TO_TEMPLATE;
            mMimeType = i.getType();
            mTemplatePkgName = i.getStringExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME);
            mTemplateSupportImgNum = i.getIntExtra(ActionConstant.Extras.EXTRA_IMAGE_NUM, 0);
            if (mTemplateSupportImgNum > 0) {
                mSelectImgTotalNum = mTemplateSupportImgNum;
                mSelectVideoTotalNum = mTemplateSupportImgNum;
            }
            mCollageBitmapBeans = new ArrayList<BitmapBean>();
        } else if (ActionConstant.Actions.ACTION_SELECT_SCREEN_LOCK_BG.equals(action)) {
            mIntentMode = INTENT_ACTION_PICK_SCREEN_LOCK_BG;
            mMimeType = i.getType();
            mCollageBitmapBeans = new ArrayList<>();
        } else if (ActionConstant.Actions.ACTION_CHANGE_IMAGES_TO_COLLAGE.equals(action)) {
            mIntentMode = INTENT_ACTION_CHANGE_TO_COLLAGE;
            mMimeType = i.getType();
        } else if (ActionConstant.Actions.ACTION_CHANGE_IMAGES_TO_FREESTYLE.equals(action)) {
            mIntentMode = INTENT_ACTION_CHANGE_TO_FREESTYLE;
            mSupportGifForFreestyle = getIntent().getBooleanExtra(ActionConstant.Extras.EXTRA_SUPPORT_GIF, true);
            mMimeType = i.getType();
        } else if (ActionConstant.Actions.ACTION_PICK_TO_EDIT.equals(action)) {//这种类型没有mMimeType的
            mIntentMode = INTENT_ACTION_PICK_TO_EDIT;
        } else if (ActionConstant.Actions.ACTION_PICK_TO_EDIT_AND_PUBLISH.equals(action)) {
            mIntentMode = INTENT_ACTION_PICK_TO_EDIT_AND_PUBLISH;
        } else if(ActionConstant.Actions.ACTION_PICK_TO_ADD_STICKER_EDIT.equals(action)) {
            mIntentMode = INTENT_ACTION_PICK_TO_ADD_STICKER;
            mMimeType = i.getType();
            mStickerPkgName = i.getStringExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME);
            mGifTitle = i.getStringExtra(ActionConstant.Extras.EXTRA_GIF_TITLE);
            mAutoScrollPosition = i.getIntExtra(ActionConstant.Extras.EXTRA_AUTO_SCROLL_POSITION, -1);
        } else if (ActionConstant.Actions.ACTION_PICK_TO_APPLY_FILTER.equals(action)) {
            mIntentMode = INTENT_ACTION_PICK_TO_APPLY_FILTER;
            mMimeType = i.getType();
            mFilterPkgName = i.getStringExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME);
            mFilerCategoryId = i.getStringExtra(ActionConstant.Extras.EXTRA_CATEGORY_ID);
        } else if (ActionConstant.Actions.ACTION_PICK_TO_BEAUTY_EDIT.equals(action)) {
            mIntentMode = INTENT_ACTION_PICK_TO_BEAUTY_EDIT;
        } else if (ActionConstant.Actions.ACTION_PICK_TO_BEAUTY_OR_BODY_FUNTION_EDIT.equals(action)) {
            mIntentMode = INTENT_ACTION_PICK_TO_BEAUTY_OR_BODY_FUNTION_EDIT;
        } else {
            mIntentMode = INTENT_ACTION_NONE;
            mMimeType = null;
        }

        mMainButtonEntrance = i.getStringExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE);
//        if ((!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face"))){//face 进入
//            mIntentMode = INTENT_ACTION_PICK_TO_EDIT;
//        }

        if (mIntentMode == INTENT_ACTION_PICK
                || mIntentMode == INTENT_ACTION_GET_CONTENT
                || mIntentMode == INTENT_ACTION_ADD_FOR_FREESTYLE
                || mIntentMode == INTENT_ACTION_CHANGE_TO_COLLAGE
                || mIntentMode == INTENT_ACTION_CHANGE_TO_FREESTYLE) {
            mIsNeedExitPageAd = false;
        }

        if (mIntentMode == INTENT_ACTION_NONE) {
            statisticsStr = "gallery";
        } else if (mIntentMode == INTENT_ACTION_PICK) {
            statisticsStr = "pick";
        } else if (mIntentMode == INTENT_ACTION_GET_CONTENT) {
            statisticsStr = "get_content";
        } else if (mIntentMode == INTENT_ACTION_PICK_TO_EDIT
                || mIntentMode == INTENT_ACTION_PICK_TO_EDIT_AND_PUBLISH
                || mIntentMode == INTENT_ACTION_PICK_TO_EDIT_AND_SHARE
                || mIntentMode == INTENT_ACTION_PICK_SCREEN_LOCK_BG) {
            statisticsStr = "edit";
        } else if (mIntentMode == INTENT_ACTION_PICK_TO_COLLAGE
                || mIntentMode == INTENT_ACTION_CHANGE_TO_COLLAGE) {
            statisticsStr = "collage";
        } else if (mIntentMode == INTENT_ACTION_PICK_TO_FREESTYLE
                || mIntentMode == INTENT_ACTION_ADD_FOR_FREESTYLE
                || mIntentMode == INTENT_ACTION_CHANGE_TO_FREESTYLE) {
            statisticsStr = "freestyle";
        } else if (mIntentMode == INTENT_ACTION_PICK_TO_BEAUTY_EDIT) {
            statisticsStr = "beauty";
        } else if (mIntentMode == INTENT_ACTION_PICK_TO_ADD_STICKER
                || mIntentMode == INTENT_ACTION_PICK_TO_APPLY_FILTER
                || mIntentMode == INTENT_ACTION_PICK_TO_TEMPLATE) {
            statisticsStr = "effect";
        }
        StatisticsUtils.statisicsCustomFunction("gallery_in", "where", statisticsStr);

        if (getIntent() != null) {
            mEntrance = getIntent().getStringExtra(EXTRA_ENTRANCE);
        }
    }

    public String getStatisticsStr() {
        return statisticsStr;
    }

    private void initView() {
        mLoadingView = findViewById(R.id.lottie_detecting);
        mCoverView = findViewById(R.id.cover_detecting);
        mContent = (RelativeLayout) findViewById(R.id.content);
        mViewPager = (ScrollLimitViewPager) findViewById(R.id.viewpager);
        mTitle = (TextView) findViewById(R.id.title);
        mBackBt = (ImageView) findViewById(R.id.back);

        //top panel
        mTopPanel = findViewById(R.id.top_panel);
        mPhotoBt = (ImageView) findViewById(R.id.photo_bt);

        if (mIntentMode == INTENT_ACTION_NONE) {
        } else {//action get content  he pick
//            mPhotoBt.setVisibility(View.INVISIBLE);
        }

        mSelectBanner = findViewById(R.id.select_banner);

        //checked top panel
        mCheckedTopPanel = findViewById(R.id.checked_top_panel);
        mCancelBt = (ImageView) findViewById(R.id.cancel);
        mNumLayout = findViewById(R.id.num_layout);
        mNumTv = (TextView) findViewById(R.id.num);
        mSuperscript = (ImageView) findViewById(R.id.superscript);
        mShareBt = (ImageView) findViewById(R.id.share);
        mDeleteBt = (ImageView) findViewById(R.id.delete);
        mSelectLayout = (LinearLayout) findViewById(R.id.select_layout);
        mLineBottom = findViewById(R.id.line_bottom);
        mScrollView = (HorizontalScrollView) findViewById(R.id.scrollView);
        mScrollLayout = (LinearLayout) findViewById(R.id.scrollView_layout);
        mSelectTip = (TextView) findViewById(R.id.select_tips);
        mNext = (RippleTextView) findViewById(R.id.select_next);
        FontUtil.setCustomFontBold(mNext);
        if (isPickToCollageMode() || isPickScreenLockBg()) {
            mSelectLayout.setVisibility(View.VISIBLE);
            mLineBottom.setVisibility(View.VISIBLE);
            if (mSelectImgTotalNum == 1) {
                mSelectTip.setText(getString(R.string.select_photo_video_one, mSelectImgTotalNum, 0));
            } else {
                mSelectTip.setText(getString(R.string.select_photos_videos, mSelectImgTotalNum, 0));
            }
            if (isPickScreenLockBg()) {
                ViewGroup.LayoutParams layoutParams = mNext.getLayoutParams();
                layoutParams.width = DeviceUtils.dip2px(100);
                mNext.setText(R.string.set_custom_lock_background);
            }
        }

        if (isPickToFreeStyle() || isAddImage4Freestyle() || isPickToCollageMode4Template()) {
            mSelectLayout.setVisibility(View.VISIBLE);
            mLineBottom.setVisibility(View.VISIBLE);
            if (mSelectImgTotalNum == 1) {
                mSelectTip.setText(getString(R.string.select_photo_one, mSelectImgTotalNum, 0));
            } else {
                mSelectTip.setText(getString(R.string.select_photos, mSelectImgTotalNum, 0));
            }
            if (isAddImage4Freestyle()) {
                ViewGroup.LayoutParams layoutParams = mNext.getLayoutParams();
                layoutParams.width = DeviceUtils.dip2px(100);
                mNext.setText(R.string.set_custom_lock_background);
            }
        }

        mBtnDeleteAll = (RippleTextView) findViewById(R.id.select_delete_all);
        FontUtil.setCustomFont(mBtnDeleteAll);

        //select baner
//		mAlbumLayout = findViewById(R.id.my_album_layout);
        mFace = (TextView) findViewById(R.id.face);
        mAlbumTv = (TextView) findViewById(R.id.my_album);
//		mPrivateLayout = findViewById(R.id.private_album_layout);
        mOtherTv = (TextView) findViewById(R.id.other_album);

        mLineLayout = findViewById(R.id.line_layout);
        mGalleryLine = findViewById(R.id.gallery_baner_line);

        mPageListenr = new MyOnPageChangeListener();

        mViewPager.setOnPageChangeListener(mPageListenr);

        mSelectColor = getResources().getColor(R.color.gallery_select_banner_selected_text_color);
        mUnSelectColor = getResources().getColor(R.color.gallery_select_banner_text_color);

        mFragments = new ArrayList<>();
//        if(!TextUtils.isEmpty(mMainButtonEntrance)) {//主页进入
//            mFragments.add(new GalleryFragment(mListener, mFragmentChangeListener, this));
//            mFragments.add(new OtherGalleryFragment(mListener, mFragmentChangeListener, this));
//        }
        DLog.d("wLog", "GalleryActivity mEntrance: " + mEntrance);
        if (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face")) {//face
            FaceGalleryFragment faceGalleryFragment = new FaceGalleryFragment(mListener, mFragmentChangeListener, this);
            if (!TextUtils.isEmpty(mEntrance) && mEntrance.contains("main_page_")) {
                //此处仅统计点击功能卡片素材进入的相册页
                switch (mEntrance) {
                    case "main_page_aging":
                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_FALBUMSHOW, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_AGING);
                        break;
                    case "main_page_gender_swap":
                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_FALBUMSHOW, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_GENDER);
                        break;
                    case "main_page_past_life":
                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_FALBUMSHOW, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_PAST);
                        break;
                }
            }
            if (!TextUtils.isEmpty(mEntrance)) {
                //只有从换性进入，mEntrance才不为空
                Bundle bundle = new Bundle();
                bundle.putString("fromWhere", mEntrance);
                faceGalleryFragment.setArguments(bundle);
            }
            mFragments.add(faceGalleryFragment);
        } else {
            GalleryFragment galleryFragment = new GalleryFragment(mListener, mFragmentChangeListener, this);
            OtherGalleryFragment otherGalleryFragment = new OtherGalleryFragment(mListener, mFragmentChangeListener, this);
            if (!TextUtils.isEmpty(mEntrance)) {
                //此处仅统计点击功能按钮或通过素材进入的相册页
                //非脸部相册页有且只有唯一主页入口
                switch (mEntrance) {
                    case "main_page_editor_filter":
                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_NFALBUMSHOW, STATISTIC_KEY_NFEDITENTER, STATISTIC_VALUE_FILTER);
                        break;
                    case "main_page_editor_floating":
                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_NFALBUMSHOW, STATISTIC_KEY_NFEDITENTER, STATISTIC_VALUE_EDIT);
                        break;
                }
                //只有从换性进入，mEntrance才不为空
                Bundle bundle = new Bundle();
                bundle.putString("fromWhere", mEntrance);
                galleryFragment.setArguments(bundle);
                otherGalleryFragment.setArguments(bundle);
            }
            mFragments.add(galleryFragment);
            mFragments.add(otherGalleryFragment);
        }

        mPageAdapter = new GalleryFragmentPageAdapter(getSupportFragmentManager(), mFragments);
        mViewPager.setOffscreenPageLimit(mPageAdapter.getCount() - 1);
        mViewPager.setAdapter(mPageAdapter);
        mViewPager.setCanScroll(true);
        Intent i = getIntent();
        mType = i.getIntExtra(TYPE, TYPE_FRAGMENT_GALLERY);

        mSettingAndMoveIn = i.getBooleanExtra(WITH_DATA, false);

        if (mSettingAndMoveIn) {
            mCheckedList = new ArrayList<ThumbnailBean>(1);
            BitmapBean bean = i.getParcelableExtra(DATA);
            if (bean != null) {
                ThumbnailBean thumbnailBean = new ThumbnailBean();
                thumbnailBean.setUri(bean.mUri);
                thumbnailBean.setType(bean.mType);
                thumbnailBean.setDate(bean.mDate);
                thumbnailBean.setDegree(bean.mDegree);
                thumbnailBean.setPath(bean.mPath);
                mCheckedList.add(thumbnailBean);
            } else {
                mSettingAndMoveIn = false;
                mCheckedList = null;
            }
        }
        FontUtil.setCustomFontBold(mTitle);
        FontUtil.setCustomFont(mFace, mAlbumTv, mOtherTv, mNumTv, mSelectTip);
        onThemeChanged();

        initIndicator();
    }

    private void initIndicator() {
        if (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face")) {//face
            findViewById(R.id.face).setVisibility(View.VISIBLE);
            findViewById(R.id.select_banner).setVisibility(View.GONE);
        } else {
            findViewById(R.id.face).setVisibility(View.GONE);
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) findViewById(R.id.other_baner_line).getLayoutParams();
            lp.weight = 1;
            findViewById(R.id.other_baner_line).setLayoutParams(lp);
        }
    }

    @Override
    public void startDetect() {
        showLoadingAnim();
    }

    @Override
    public void endDetect() {
        hideLoadingAnim();
    }

    private void showLoadingAnim() {
        mCoverView.setVisibility(View.VISIBLE);
        mLoadingView.setVisibility(View.VISIBLE);
        mLoadingView.playAnimation();
    }

    private void hideLoadingAnim() {
        mCoverView.setVisibility(View.GONE);
        mLoadingView.cancelAnimation();
        mLoadingView.setVisibility(View.GONE);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @OnClick(R.id.num_layout)
    void onNumLayoutClicked() {
        setShareViewGone();
        mNumLayoutChecked = !mNumLayoutChecked;
        doCheckAll(mNumLayoutChecked);
    }

    @OnClick(R.id.back)
    void onBackBtnClicked() {
        if (!mFragments.get(mType).onBackClick(mBackBt)) {
            stasticQuitEvent();
            TaskRunnable runnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                @Override
                public void run() {
                    statisticsMainBtnAlbumBack();
                    finish();
                }
            };
//            if (mGalleryExitAdProvider != null) {
//                mGalleryExitAdProvider.onExit(runnable);
//            } else {
            runnable.runSelfAdaptation();
//            }
        }
    }

    @Override
    public void onBackPressed() {
//        if (mGalleryExitAdProvider != null) {
//            mGalleryExitAdProvider.onExit(null);
//        }
        super.onBackPressed();
        stasticQuitEvent();
    }

    private void stasticQuitEvent() {
        if (!TextUtils.isEmpty(mEntrance)) {
            DLog.d("wLog", "Gallery quit mEntrance: " + mEntrance);
            if (TextUtils.isEmpty(mEntrance)) {

            } else if (mEntrance.contains("main_page_editor_")) {
                switch (mEntrance) {
                    case "main_page_editor_filter":
                        if (!mBackFromEdit) {
                            StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_NFALBUMQUIT, STATISTIC_KEY_NFEDITENTER, STATISTIC_VALUE_FILTER);
                        }
                        break;
                    case "main_page_editor_floating":
                        if (!mBackFromEdit) {
                            StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_NFALBUMQUIT, STATISTIC_KEY_NFEDITENTER, STATISTIC_VALUE_EDIT);
                        }
                        break;
                }
            } else if (mEntrance.contains("main_page_")){
                switch (mEntrance) {
                    case "main_page_aging":
                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_FALBUMQUIT, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_AGING);
                        break;
                    case "main_page_gender_swap":
                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_FALBUMQUIT, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_GENDER);
                        break;
                    case "main_page_past_life":
                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_FALBUMQUIT, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_PAST);
                        break;
                }
            }
        }
    }

    @OnClick(R.id.cancel)
    void onCancelBtnClicked() {
        mFragments.get(mType).onCancelClick(mCancelBt);
    }

    @OnClick(R.id.share)
    void onShareBtnClicked() {
        mFragments.get(mType).onShareClick(mShareBt);
    }

    @OnClick(R.id.delete)
    void onDeleteBtnClicked() {
        setShareViewGone();
        mFragments.get(mType).onDeleteClick(mDeleteBt);
    }

    @OnClick(R.id.face)
    void onFaceBtnClicked() {
        if (mType != TYPE_FRAGMENT_FACE) {
            showFragment(TYPE_FRAGMENT_FACE);
        }
    }

    @OnClick(R.id.my_album)
    void onAlbumBtnClicked() {
        if (mType != TYPE_FRAGMENT_GALLERY) {
            showFragment(TYPE_FRAGMENT_GALLERY);
        }
    }

    @OnClick(R.id.photo_bt)
    void onPhotoBtnClicked() {
        //TODO:跳转系统相机
        mFragmentChangeListener.onDataChange(TYPE_FRAGMENT_FACE);
        mFragmentChangeListener.onDataChange(TYPE_FRAGMENT_GALLERY);
        mFragmentChangeListener.onDataChange(TYPE_FRAGMENT_OTHER_GALLERY);
        overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
    }

    @OnClick(R.id.other_album)
    void onOtherAlbumBtnClicked() {
        if (mType != TYPE_FRAGMENT_OTHER_GALLERY) {
            setShareViewGone();
            showFragment(TYPE_FRAGMENT_OTHER_GALLERY);
        }
    }

    @OnClick(R.id.select_next)
    void onSelectNextBtnClicked() {
        if (mCollageBitmapBeans.size() > 0) {
            TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                @Override
                public void run() {
                    /*if (isPickToCollageMode4Template()) {
                        if (TextUtils.isEmpty(mTemplatePkgName)) {
                            CollageActivity.startCollageActivity(GalleryActivity.this, mCollageBitmapBeans, REQUEST_CODE_TEMPLATE, mMainButtonEntrance);
                        } else {
                            if (mCollageBitmapBeans.size() == mTemplateSupportImgNum) {
                                CollageActivity.startCollageActivity(GalleryActivity.this, mCollageBitmapBeans, mTemplatePkgName, REQUEST_CODE_TEMPLATE, mMainButtonEntrance);
                            } else {
//                        Toast.makeText(this, getString(R.string.select_image_num_tip, mTemplateSupportImgNum), Toast.LENGTH_SHORT).show();
                                // TODO: 2019/5/8 自动复制图片，从第一张图片开始复制，直到满足模板要求数量
                                copyImage();
                                CollageActivity.startCollageActivity(GalleryActivity.this, mImageList, mTemplatePkgName, REQUEST_CODE_TEMPLATE, mMainButtonEntrance);
                            }
                        }
                    } else if (isPickToFreeStyle()) {
                        FreeStyleActivity.startCollageActivity(GalleryActivity.this, mCollageBitmapBeans, REQUEST_CODE_COLLAGE, mMainButtonEntrance);
                    } else */
                    if (isAddImage4Freestyle()) {
                        Intent data = getIntent();
                        Bundle bundle = new Bundle();
                        bundle.putParcelableArrayList(IMAGE_DATA, mCollageBitmapBeans);
                        data.putExtra(IMAGE_DATA, bundle);
                        setResult(Activity.RESULT_OK, data);
                        finish();
                    } /*else {
                        if (mCollageBitmapBeans.size() == 1 && (mCollageBitmapBeans.get(0).mType == MediaTypeUtil.TYPE_VIDEO
                                || mCollageBitmapBeans.get(0).mType == MediaTypeUtil.TYPE_GIF)) {
                            ToastUtil.showToast(R.string.at_least_two_video);
                            return;
                        }
                        if (mBackgroundCategoryName != null) {
                            CollageActivity.startCollageActivityWithBackground(GalleryActivity.this, mCollageBitmapBeans, mBackgroundCategoryName, mBackgroundItemName, REQUEST_CODE_COLLAGE);
                        } else {
                            CollageActivity.startCollageActivity(GalleryActivity.this, mCollageBitmapBeans, REQUEST_CODE_COLLAGE, mMainButtonEntrance);
                        }
                    }*/
                    statisticsMainBtnAlbumStart();
                }
            };
            showAd(taskRunnable);
        } else {
            ToastUtil.showToast(R.string.at_least_one_photo);
        }
    }

    public void showAd(TaskRunnable taskRunnable) {
        if (taskRunnable != null) {
            taskRunnable.runSelfAdaptation();
        }
    }

    @OnClick(R.id.select_delete_all)
    void onSelectDeleteAllBtnClick() {
        if (mCollageBitmapBeans.size() > 0) {
            mCollageBitmapBeans.clear();
            mScrollLayout.removeAllViews();
            if (mSelectImgTotalNum == 1) {
                if (isPickToFreeStyle() || isAddImage4Freestyle() || isPickToCollageMode4Template()) {
                    mSelectTip.setText(getString(R.string.select_photo_one, mSelectImgTotalNum, mCollageBitmapBeans.size()));
                } else {
                    mSelectTip.setText(getString(R.string.select_photo_video_one, mSelectImgTotalNum, mCollageBitmapBeans.size()));
                }
            } else {
                if (isPickToFreeStyle() || isAddImage4Freestyle() || isPickToCollageMode4Template()) {
                    mSelectTip.setText(getString(R.string.select_photos, mSelectImgTotalNum, mCollageBitmapBeans.size()));
                } else {
                    mSelectTip.setText(getString(R.string.select_photos_videos, mSelectImgTotalNum, mCollageBitmapBeans.size()));
                }
            }
            mBtnDeleteAll.setVisibility(View.GONE);
            for (SelectBean selectBean : mSelectBeanList) {
                selectBean.mThumbnailBean.setSelectCount(0);
            }
            if (mFragments != null && mFragments.get(TYPE_FRAGMENT_FACE) != null
                    && mFragments.get(TYPE_FRAGMENT_FACE).getAdapter() != null && (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face"))) {
                mFragments.get(TYPE_FRAGMENT_FACE).getAdapter().notifyDataSetChanged();
            }
            if (mFragments != null && mFragments.get(TYPE_FRAGMENT_GALLERY) != null
                    && mFragments.get(TYPE_FRAGMENT_GALLERY).getAdapter() != null) {
                mFragments.get(TYPE_FRAGMENT_GALLERY).getAdapter().notifyDataSetChanged();
            }
            if (mFragments != null && mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY) != null
                    && mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY).getAdapter() != null) {
                mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY).getAdapter().notifyDataSetChanged();
            }
        }
    }

    private void setShareViewGone() {
        //这个处理是防止分享时切Tab导致的错误
        if (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face")) {
            FaceGalleryFragment f = ((FaceGalleryFragment) mFragments.get(TYPE_FRAGMENT_FACE));
            f.setShareViewGone();
        }
        GalleryFragment gf = ((GalleryFragment) mFragments.get(TYPE_FRAGMENT_GALLERY));
        gf.setShareViewGone();
        OtherGalleryFragment ogf = ((OtherGalleryFragment) mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY));
        ogf.setShareViewGone();
    }

    private void restoreOtherGalleryMode() {
        OtherGalleryFragment ogf = ((OtherGalleryFragment) mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY));
        ogf.modeChangeListener.onModeChange(OtherGalleryFragment.MODE_FOLDER, -1);
    }

    /**
     * 处理点击cancel
     */
    public void doCancel(ListGridAdapter adapter) {
        mNumLayoutChecked = false;
        adapter.setCheckStatus(false);
    }

    /**
     * 处理点击cancel
     */
    public void doCancel(FolderListAdapter adapter) {
        mNumLayoutChecked = false;
        adapter.setCheckStatus(false);
    }

    /**
     * 处理点击cancel
     */
    private void doCheckAll(boolean checked) {
        if (mType == TYPE_FRAGMENT_OTHER_GALLERY) {
            OtherGalleryFragment ogf = ((OtherGalleryFragment) mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY));
            ogf.doCheckAll(checked);
        } else {
            ListGridAdapter adapter = mFragments.get(mType).getAdapter();
            if (adapter != null) {
                adapter.checkAll(checked);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mToday = getString(R.string.today);
        mYesterday = getString(R.string.yesterday);
        mMonth = getString(R.string.this_month);
        TODAY_KEY = mToday;
        YESTERDAY_KEY = mYesterday;
        MONTH_KEY = mMonth;
        mFragments.get(mType).doOnStart();

//        if(mBackUpDialog != null && mBackUpDialog.isShowing()){
//            mBackUpDialog.dismiss();
//        }
//
//        if(mRecoveryDialog != null && mRecoveryDialog.isShowing()){
//            mRecoveryDialog.dismiss();
//        }
    }

    public void startImagePreviewActivity(ThumbnailBean bean) {
        mFragments.get(mType).startImagePreviewActivity(bean, REQUEST_CODE_PREVIEW);
    }

    /**
     * 展示页面
     *
     * @param type
     */
    public void showFragment(int type) {
        ListGridAdapter adapter = mFragments.get(mType).getAdapter();
        if (adapter != null) {
            doCancel(adapter);
        }
        if (TextUtils.isEmpty(mMainButtonEntrance) || !mMainButtonEntrance.equals("face")) {//主页进入
            OtherGalleryFragment ogf = (OtherGalleryFragment) mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY);
            ogf.doCancel();
        }
//        restoreOtherGalleryMode();
        mPageListenr.setType(type);
        if (type == TYPE_FRAGMENT_FACE && (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face"))) {
            mType = TYPE_FRAGMENT_FACE;
            mViewPager.setCurrentItem(mType, false);
            mFragments.get(mType).refreshData();
            updateUI(type);
        } else if (type == TYPE_FRAGMENT_GALLERY) {
            mType = TYPE_FRAGMENT_GALLERY;
            mViewPager.setCurrentItem(mType, false);
            mFragments.get(mType).refreshData();
            updateUI(type);
        } else if (type == TYPE_FRAGMENT_OTHER_GALLERY) {
            mType = TYPE_FRAGMENT_OTHER_GALLERY;
            mViewPager.setCurrentItem(mType, false);
            mFragments.get(mType).refreshData();
            updateUI(type);
        }
    }

    private void dealSelectFragment(int type) {
        ListGridAdapter adapter = mFragments.get(mType).getAdapter();
        if (adapter != null) {
            doCancel(adapter);
        }
        OtherGalleryFragment ogf = (OtherGalleryFragment) mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY);
        ogf.doCancel();
//        restoreOtherGalleryMode();
        if (type == TYPE_FRAGMENT_FACE && (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face"))) {
            mType = TYPE_FRAGMENT_FACE;
            mFragments.get(mType).refreshData();
            updateUI(type);
        } else if (type == TYPE_FRAGMENT_GALLERY) {
            mType = TYPE_FRAGMENT_GALLERY;
            mFragments.get(mType).refreshData();
            updateUI(type);
        } else if (type == TYPE_FRAGMENT_OTHER_GALLERY) {
            mType = TYPE_FRAGMENT_OTHER_GALLERY;
            mFragments.get(mType).refreshData();
            updateUI(type);
        }
    }

    /**
     * 切换fragment时更新界面UI
     *
     * @param type
     */
    private void updateUI(int type) {
        if (type == TYPE_FRAGMENT_FACE && (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face"))) {
            mTitle.setText(R.string.face);
            mShareBt.setVisibility(View.VISIBLE);
            mFace.setTextColor(mSelectColor);
            mAlbumTv.setTextColor(mUnSelectColor);
            mOtherTv.setTextColor(mUnSelectColor);
        } else if (type == TYPE_FRAGMENT_GALLERY) {
            mTitle.setText(R.string.gallery);
            mShareBt.setVisibility(View.VISIBLE);
            mFace.setTextColor(mUnSelectColor);
            mAlbumTv.setTextColor(mSelectColor);
            mOtherTv.setTextColor(mUnSelectColor);
        } else if (type == TYPE_FRAGMENT_OTHER_GALLERY) {
            OtherGalleryFragment ogf = ((OtherGalleryFragment) mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY));
            if (ogf.getMode() == OtherGalleryFragment.MODE_FOLDER) {
                mTitle.setText(R.string.other_gallery);
                mShareBt.setVisibility(View.GONE);
                mFace.setTextColor(mUnSelectColor);
                mAlbumTv.setTextColor(mUnSelectColor);
                mOtherTv.setTextColor(mSelectColor);
            } else if (ogf.getMode() == OtherGalleryFragment.MODE_GALLERY) {
                mTitle.setText(ogf.getFolderName(ogf.getSelectionIndex()));
                mShareBt.setVisibility(View.VISIBLE);
                mFace.setTextColor(mUnSelectColor);
                mAlbumTv.setTextColor(mUnSelectColor);
                mOtherTv.setTextColor(mSelectColor);
            }
        }
    }

    private boolean mBackFromEdit = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PREVIEW) {
            mFragments.get(mType).onActivityResult(requestCode, resultCode, data);
        } else if ((requestCode == REQUEST_CODE_COLLAGE || requestCode == REQUEST_CODE_TEMPLATE) && resultCode == RESULT_OK) {//拼接已经完成不再需要
            finish();
        } else if (requestCode == REQUEST_CODE_PICK_TO_EDIT && resultCode == RESULT_OK) {//拼接已经完成不再需要
            finish();
        } else if (requestCode == PermissionUtil.PERMISSION_REQ_CODE) {
            if (mReqPermissionFromSetting) {
                boolean result = PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                StatisticsUtils.statisicsCustomFunction(StatisticsConstant.PERMISSION_GALLERY,
                        StatisticsConstant.PERMISSION_GALLERY_KEY_STORAGE_CLICK, String.valueOf(!result));
                mReqPermissionFromSetting = false;
                if (result) {
//                    ToastUtil.showToast(String.format(getString(R.string.permission_storage_error),
//                            getString(R.string.app_name)));
                    finish();
                }
            }
        } else if (requestCode == REQUEST_CODE_TAKEPHOTO) {//拍照返回
            FaceGalleryFragment.fromFaceFragment=false;
            if (resultCode == RESULT_OK) {
                String photoPath = SpUtils.obtain().getString("camera_image_path", null);
                Uri uri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileUtil.getExternalFileUri(photoPath);
                } else {
                    uri = Uri.fromFile(new File(photoPath));
                }
                Log.e("tag", "contentUri: " + uri);
                Log.e("tag", "photoPath: " + photoPath);
                //refresh gallery
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).setData(uri));
                //
                if (mPageAdapter.currentFragment instanceof FaceGalleryFragment) {
                    if (SpUtils.obtain().getBoolean("first_edit", true)) {
                        showPrivateDialog(photoPath, uri);
                        return;
                    }
                }
                takePhotoBack(photoPath, uri);
            }
        } else if (requestCode == REQUEST_CODE_PICK_TO_EDIT && resultCode == RESULT_CANCELED) {  //face拍照后不编辑返回
            mBackFromEdit = true;
//            finish();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean result = false;
        if (requestCode == PermissionUtil.PERMISSION_REQ_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED
                        && permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    result = true;
                }
            }
            StatisticsUtils.statisicsCustomFunction(StatisticsConstant.PERMISSION_GALLERY,
                    StatisticsConstant.PERMISSION_GALLERY_KEY_STORAGE_CLICK, String.valueOf(result));
            if (result) {
                // 用户授权，刷新界面数据
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mFragments != null) {
                            for (XFragment fragment : mFragments) {
                                fragment.forceRefreshData();
                            }
                        }
                    }
                });
            } else {
//                ToastUtil.showToast(String.format(getString(R.string.permission_storage_error),
//                        getString(R.string.app_name)));
//                finish();
            }
        }else if (requestCode == PERMISSION_CAMERA_CODE){
            for (int i=0; i<grantResults.length; i++ ){
                if (grantResults[i] == PackageManager.PERMISSION_DENIED){  //用户选择了拒绝
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])){  //勾选不再提示
                        if (ContextCompat.checkSelfPermission(this,  permissions[i]) != PackageManager.PERMISSION_GRANTED){
                            //引导用户至设置页手动授权
                            ToastUtil.showToast(R.string.permission_camera_tips);
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", AppApplication.getApplication().getPackageName(), null);
                            intent.setData(uri);
                            startActivity(intent);
                            SpUtils.obtain().save(SP_REJECT_CAMERA_PERMISSION, true);
                        }
                    }
                    break;
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFacePrivacyPolicyEvent(FacePrivacyPolicyEvent event) {
        if (event == null || event.getOnClickListener() == null) {
            return;
        }
        showPrivateDialog(event.getOnClickListener());
    }

    //隐私弹窗
    public void showPrivateDialog(final String path, final Uri uri) {
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhotoBack(path, uri);
            }
        };
        showPrivateDialog(onClickListener);
    }

    private void showPrivateDialog(final View.OnClickListener onClickListener) {
        TextView tvLink = new TextView(this);
        tvLink.setText(getResources().getString(R.string.face_privacy_poicy));
        tvLink.setTextColor(Color.parseColor("#1b1b1b"));
        tvLink.setPadding(72, 32, 0, 0);
        tvLink.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tvLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //todo goto隐私协议
                AndroidDevice.startWebView(GalleryActivity.this, Global.PRIVACY_URL);
            }
        });

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.face_privacy_poicy_tips))
                .setMessage(getResources().getString(R.string.face_privacy_poicy_message))
                .setView(tvLink)
                .setNegativeButton(getResources().getString(R.string.face_privacy_poicy_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setPositiveButton(getResources().getString(R.string.face_privacy_poicy_agree), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SpUtils.obtain().save("first_edit", false);
                        //拍照回调
                        if (onClickListener != null) {
                            onClickListener.onClick(null);
                        }
                    }
                })
                .show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.GRAY);
    }

    private void takePhotoBack(String path, Uri uri) {
        if (path == null || uri == null) {
            return;
        }
//        if (uri != null){
//            String tempPath = getPath(this, uri);
//            if (tempPath != null){
        int degree = getBitmapDegree(path);

        //根据角度旋转图片为正，并覆盖原图
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        if (bitmap != null) {
            Bitmap bitmap1 = rotateBitmap(bitmap, degree);
            if (bitmap1 != null) {
                if (saveBmpToPath(bitmap1, path)) {
                    degree = 0;
                }
            }
        }

        Log.e("tag", "degree: " + degree);

        ThumbnailBean thumbnailBean = new ThumbnailBean(path, System.currentTimeMillis(),
                false, uri, degree, MediaTypeUtil.TYPE_JPG);
//                if (mPageAdapter.currentFragment instanceof FaceFragment){
////                    mPageAdapter.currentFragment.forceRefreshData();
//                    ((FaceFragment) mPageAdapter.currentFragment).takePhotoBack(thumbnailBean);
//                }else if (mPageAdapter.currentFragment instanceof GalleryFragment){
//                    mPageAdapter.currentFragment.forceRefreshData();
//                    ((GalleryFragment) mPageAdapter.currentFragment).takePhotoBack(thumbnailBean);
//                }
        if (mType == TYPE_FRAGMENT_FACE && (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face"))) {
            ((FaceGalleryFragment) mFragments.get(0)).takePhotoBack(thumbnailBean);
        } else {
            ((GalleryFragment) mFragments.get(0)).forceRefreshData();
            ((GalleryFragment) mFragments.get(0)).takePhotoBack(thumbnailBean);
        }
//            }
//        }
    }

    /**
     * 读取图片的旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片的旋转角度
     */
    public static int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 专为Android4.4及以上设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * 旋转图片
     *
     * @param bitmap rotate
     * @return 返回类型
     * //     * @exception 异常描述
     * //     * @see 需要参见的其它内容
     * @deprecated该方法从类的那一个版本后，已经被其它方法替换。（可选）
     * @since 从类的哪一个版本，此方法被添加进来。（可选）
     */
    public Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
        if (bitmap == null)
            return null;

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        // Setting post rotate to 90
        Matrix mtx = new Matrix();
        mtx.postRotate(rotate);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
    }

    /**
     * @param bitmap   要保存的图片
     * @param filePath 目标路径
     * @return 是否成功
     * @Description 保存图片到指定路径
     */
    @SuppressWarnings("finally")
    public static boolean saveBmpToPath(final Bitmap bitmap, final String filePath) {
        if (bitmap == null || filePath == null) {
            return false;
        }
        boolean result = false; // 默认结果
        File file = new File(filePath);
        OutputStream outputStream = null; // 文件输出流
        try {
            outputStream = new FileOutputStream(file);
            result = bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    outputStream); // 将图片压缩为JPEG格式写到文件输出流，100是最大的质量程度
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close(); // 关闭输出流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mFragments.get(mType).onKeyUp(keyCode, event)) {
                return true;
            } else {
                statisticsBack();
            }
        }
        return super.onKeyUp(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mMediaChangeObserver == null) {
            mMediaChangeObserver = new ContentObserver(mMainHandler) {
                @Override
                public void onChange(boolean selfChange) {
                    if (mFragments != null) {
                        for (XFragment fragment : mFragments) {
                            fragment.forceRefreshData();
                        }
                    }
                }
            };
            getContentResolver().registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                    , false
                    , mMediaChangeObserver);
        }

    }

    public void changUIForMode(int mode, int position) {
        if (mode == OtherGalleryFragment.MODE_FOLDER) {
            mTitle.setText(R.string.other_gallery);
            mShareBt.setVisibility(View.GONE);
        } else if (mode == OtherGalleryFragment.MODE_GALLERY) {
            mShareBt.setVisibility(View.VISIBLE);
            OtherGalleryFragment ogf = (OtherGalleryFragment) mFragments.get(TYPE_FRAGMENT_OTHER_GALLERY);
            mTitle.setText(ogf.getFolderName(position));
        }
    }


    /**
     * 创建Widget的dialog
     */
    public void showCreateWidgetDialog(final boolean isUser) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.tip)
                .setMessage(R.string.create_widget_content)
                .setPositiveButton(R.string.create_widget_bt_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }


    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        int type = mType;
        boolean isScrolling = false;

        //        boolean isRight = mType == TYPE_FRAGMENT_GALLERY ? true : false;
//        int lastValue = isRight ? 0 : ImageHelper.SCREEN_WIDTH;
        @Override
        public void onPageSelected(int arg0) {
            if (arg0 != mType) {
                type = arg0;
                dealSelectFragment(type);
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            Log.e("lai", arg0 + "..." + arg1 + "..." + arg2);
            mLineLayout.scrollTo(-(ImageHelper.SCREEN_WIDTH / mPageAdapter.getCount() * arg0 + arg2 / mPageAdapter.getCount()), 0);
//            if(isScrolling && lastValue != -1){
//                if (lastValue > arg2) {
//                    isRight = false;
//                } else if(lastValue < arg2){
//                    isRight = true;
//                }
//            }
//            if(lastValue != -1){
//                if(arg2 != 0){
//                    if(type == 0){
//                        mLineLayout.scrollTo(-arg2 / 2, 0);
//                    } else if(type == 1){
//                        if(isRight){
//                            if(arg0 == 0){
//                                mLineLayout.scrollTo(- arg2 / 2, 0);
//                            } else if(arg0 == 1){
//                                mLineLayout.scrollTo(-ImageHelper.SCREEN_WIDTH / 2 - arg2 / 2, 0);
//                            }
//                        } else{
//                            if(arg0 == 0){
//                                mLineLayout.scrollTo(- arg2 / 2, 0);
//                            } else if(arg0 == 1){
//                                mLineLayout.scrollTo(-ImageHelper.SCREEN_WIDTH / 2 - arg2 / 2, 0);
//                            }
//                        }
//                    } else if(type == 2){
//                        mLineLayout.scrollTo(-ImageHelper.SCREEN_WIDTH / 2 - arg2 / 2, 0);
//                    }
//                }
//            }
//            lastValue = arg2;
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            if (arg0 == 1) {
                isScrolling = true;
            } else {
                isScrolling = false;
            }
            if (arg0 == 0) {
                setType(mType);
            }
        }

        public void setType(int t) {
            if (t == TYPE_FRAGMENT_FACE && (!TextUtils.isEmpty(mMainButtonEntrance) && mMainButtonEntrance.equals("face"))) {
                type = TYPE_FRAGMENT_FACE;
                mLineLayout.scrollTo(0, 0);
//                lastValue = -1;
            } else if (t == TYPE_FRAGMENT_GALLERY) {
                type = TYPE_FRAGMENT_GALLERY;
                mLineLayout.scrollTo(0, 0);
//                mLineLayout.scrollTo(-ImageHelper.SCREEN_WIDTH / mPageAdapter.getCount(), 0);
//                lastValue = -1;
            } else if (t == TYPE_FRAGMENT_OTHER_GALLERY) {
                type = TYPE_FRAGMENT_OTHER_GALLERY;
//                mLineLayout.scrollTo(-ImageHelper.SCREEN_WIDTH / 2, 0);
                mLineLayout.scrollTo(-ImageHelper.SCREEN_WIDTH / mPageAdapter.getCount() * TYPE_FRAGMENT_OTHER_GALLERY, 0);
//                lastValue = -1;
            }
        }
    }


    public int getCheckedImageNum() {
        return (mCheckedAllNum - mCheckedVideoNum);
    }

    public int getCheckedVideoNum() {
        return mCheckedVideoNum;
    }

    public void onThemeChanged() {
        int childSize = mScrollLayout.getChildCount();
        for (int i = 0; i < childSize; i++) {
//            ((ImageView)(mScrollLayout.getChildAt(i).findViewWithTag("close"))).setImageResource(R.drawable.gallery_collage_close_icon);
        }
        updateUI(mType);
    }

    public static abstract class ProgressChangeListener {
        public int progress = 0;

        public void onProgressChange() {
            progress++;
        }

        ;
    }

    /**
     * 格式化数据
     *
     * @param resultBean
     * @param map
     * @param today
     */
    public synchronized ArrayList<Object> uniformData(ArrayList<ThumbnailBean> resultBean, HashMap<String, Integer> map, DateBean today, int colNum) {

        ArrayList<ThumbnailBean> result = new ArrayList<>(resultBean);

        ArrayList<Object> datas = new ArrayList<Object>();

        int l = result.size();
        if (l == 0) {
            return datas;
        }
        ArrayList<Object> data = null;
        ThumbnailBean first = result.get(0);
        DateBean now = new DateBean(first.getDate());

        int nextAdPosition = 0;

        today.setDate(System.currentTimeMillis());

        //今天减掉一天就是昨天
        DateBean yesterday = new DateBean(today.getDateTime() - (24 * 60 * 60 * 1000));

        /**
         * 处理第一个
         */
        boolean hasToday = false;
        boolean hasYesTerday = false;
        boolean hasBlewSevenDays = false;
        boolean isAllBlewSevenDays = false;
        boolean isAllToday = false;
        boolean isAllYesterday = false;
        if (now.isSameDay(today)) {
            datas.add(new SeparatorBean(mToday, GalleryActivity.TODAY_KEY));
            hasToday = true;
        } else if (now.isDurationDays(today, 7)) {//7天之内
            datas.add(new SeparatorBean(now.getMonthDayString()));
            hasBlewSevenDays = true;
        } else {
            if (now.isSameMonth(today)) {
                datas.add(new SeparatorBean(mMonth, GalleryActivity.MONTH_KEY));
            } else {
                datas.add(new SeparatorBean(now.getYearMonthString()));
            }
        }
        data = new ArrayList<Object>();
        datas.add(data);
        data.add(first);

        int i = 1;
        int dayCount = 1; //第几天
        if (hasToday) {
            int[] res = uniformDataByDayOrMonth(result, map, now, colNum, datas, dayCount, i, nextAdPosition, 1);
            i = res[0];
            nextAdPosition = res[2];
            map.put(GalleryActivity.TODAY_KEY, res[1]);
            map.put(GalleryActivity.TODAY_KEY + "_" + GalleryActivity.AD, res[3]);
            if (i < l) {
                now = new DateBean(result.get(i).getDate());

                if (now.isSameDay(yesterday)) {//有昨天
                    hasYesTerday = true;
                    datas.add(new SeparatorBean(mYesterday, GalleryActivity.YESTERDAY_KEY));
                } else if (now.isDurationDays(today, 7)) {
                    hasBlewSevenDays = true;
                    datas.add(new SeparatorBean(now.getMonthDayString()));
                } else if (now.isSameMonth(today)) {
                    datas.add(new SeparatorBean(mMonth, GalleryActivity.MONTH_KEY));
                } else {
                    datas.add(new SeparatorBean(now.getYearMonthString()));
                }
                data = new ArrayList<Object>();
                datas.add(data);
                data.add(result.get(i));
                i++;
                dayCount++;
            } else {
                isAllToday = true;
            }

            /**
             * 这种是全是Today的情况
             */
//            if(map.get(GalleryActivity.TODAY_KEY) == null){
//                isAllToday = true;
//                map.put(GalleryActivity.TODAY_KEY, res[1]);
//            }
        }

        if (hasYesTerday) {
            int[] res = uniformDataByDayOrMonth(result, map, now, colNum, datas, dayCount, i, nextAdPosition, 1);
            i = res[0];
            nextAdPosition = res[2];
            map.put(GalleryActivity.YESTERDAY_KEY, res[1]);
            map.put(GalleryActivity.YESTERDAY_KEY + "_" + GalleryActivity.AD, res[3]);
            if (i < l) {
                now = new DateBean(result.get(i).getDate());

                if (now.isDurationDays(today, 7)) {
                    hasBlewSevenDays = true;
                    datas.add(new SeparatorBean(now.getMonthDayString()));
                } else if (now.isSameMonth(today)) {
                    datas.add(new SeparatorBean(mMonth, GalleryActivity.MONTH_KEY));
                } else {
                    datas.add(new SeparatorBean(now.getYearMonthString()));
                }
                data = new ArrayList<Object>();
                datas.add(data);
                data.add(result.get(i));
                i++;
                dayCount++;
            } else {
                isAllYesterday = true;
            }

            /**
             * 这种是只有Today和Yesterday的情况
             */
//            if(map.get(GalleryActivity.YESTERDAY_KEY) == null){
//                isAllYesterday = true;
//                map.put(GalleryActivity.YESTERDAY_KEY, res[1]);
//            }
        }

        if (!isAllYesterday && hasBlewSevenDays) {
            isAllBlewSevenDays = true;
            for (; i < l; i++) {

                int[] res = uniformDataByDayOrMonth(result, map, now, colNum, datas, dayCount, i, nextAdPosition, 1);
                i = res[0];
                nextAdPosition = res[2];
                map.put(now.getMonthDayString(), res[1]);//记录数量
                map.put(now.getMonthDayString() + "_" + GalleryActivity.AD, res[3]);

                if (i < l) {
                    now = new DateBean(result.get(i).getDate());
                    if (now.isDurationDays(today, 7)) {
                        datas.add(new SeparatorBean(now.getMonthDayString()));
                        data = new ArrayList<Object>();
                        datas.add(data);
                        data.add(result.get(i));
                        dayCount++;
                    } else if (now.isSameMonth(today)) {
                        datas.add(new SeparatorBean(mMonth, GalleryActivity.MONTH_KEY));
                        data = new ArrayList<Object>();
                        datas.add(data);
                        data.add(result.get(i));
                        i++;
                        isAllBlewSevenDays = false;
                        dayCount++;
                        break;
                    } else {
                        datas.add(new SeparatorBean(now.getYearMonthString()));
                        data = new ArrayList<Object>();
                        datas.add(data);
                        data.add(result.get(i));
                        i++;
                        isAllBlewSevenDays = false;
                        dayCount++;
                        break;
                    }
                }
            }

//            if(isAllBlewSevenDays){
//                map.put(now.getMonthDayString(), sum);
//                sum = 0;
//                num = 0;
//            }
        }

        if (!isAllToday && !isAllYesterday && !isAllBlewSevenDays) {
            for (; i < l; i++) {

                int[] res = uniformDataByDayOrMonth(result, map, now, colNum, datas, dayCount, i, nextAdPosition, 2);
                i = res[0];
                nextAdPosition = res[2];
                String mapKey;
                if (now.isSameMonth(today)) {
                    mapKey = GalleryActivity.MONTH_KEY;
                } else {
                    mapKey = now.getYearMonthString();
                }
                map.put(mapKey, res[1]);
                map.put(mapKey + "_" + GalleryActivity.AD, res[3]);

                if (i < l) {
                    now = new DateBean(result.get(i).getDate());
                    datas.add(new SeparatorBean(now.getYearMonthString()));
                    data = new ArrayList<Object>();
                    datas.add(data);
                    data.add(result.get(i));
                    dayCount++;
                }
            }
            /**
             * 这里是最后一个月只有一张图片的情况
             */
            if (now.isSameMonth(today)) {
                map.put(GalleryActivity.MONTH_KEY, 1);
            } else {
                map.put(now.getYearMonthString(), 1);
            }
        }

//		for(String key: map.keySet()){
//			System.out.println("key = " + key + "  value = " + map.get(key));
//		}

        return datas;
    }

    /**
     * @param result
     * @param map
     * @param now
     * @param colNum
     * @param datas
     * @param dayCount
     * @param i
     * @param nextAdPosition
     * @param style
     * @return int[] 需回传的数据，目前分别为：
     * 1. 当前数据的位置
     * 2. 当天或当月的图片数目
     * 3. 当前广告位置
     * 4. 当天或当月的广告数目
     */
    private synchronized int[] uniformDataByDayOrMonth(ArrayList<ThumbnailBean> result, HashMap<String, Integer> map, DateBean now, int colNum,
                                                       ArrayList<Object> datas, int dayCount, int i, int nextAdPosition, int style) {

        ArrayList<Object> data;
        Object lastObject = datas.get(datas.size() - 1);
        if (lastObject instanceof ArrayList) {
            data = (ArrayList<Object>) lastObject;
        } else {
            data = new ArrayList<>();
        }

        int l = result.size();
        int sum = 1;
        int num = 1;
        int sumAd = 0;
        for (; i < l; i++) {

            DateBean next = new DateBean(result.get(i).getDate());

            if ((style == 1 && next.isSameDay(now))
                    || (style == 2 && next.isSameMonth(now))) {
                if (num < colNum) {
                    data.add(result.get(i));
                } else {
                    data = new ArrayList<Object>();
                    num = 0;
                    datas.add(data);
                    data.add(result.get(i));
                }
                num++;
                sum++;
            } else {

                break;
            }
        }
        return new int[]{i, sum, nextAdPosition, sumAd};
    }

    public int getTopicIdFromIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            return intent.getIntExtra(ActionConstant.Extras.EXTRA_TOPIC_ID, 0);
        }
        return 0;
    }

    private List<SelectBean> mSelectBeanList;

//    /**
//     * 选择图片
//     * @param thumbnailBean
//     */
//    public void addCollageBitmap(ThumbnailBean thumbnailBean, boolean checkDuplicate, int type, Bitmap thumbnail){
//        if(canSelect(thumbnailBean.getType())) {
//
//            BitmapBean bean = new BitmapBean();
//            bean.mUri = thumbnailBean.getUri();
//            bean.mType = thumbnailBean.getType();
//            bean.mPath = thumbnailBean.getPath();
//            bean.mDegree = thumbnailBean.getDegree();
//            bean.mDuration = thumbnailBean.getDuration();
//            if (checkDuplicate && mCollageBitmapBeans.contains(bean)) {
//                ToastUtil.showToast(R.string.slecet_duplicate_picture);
//                return;
//            }
//            mCollageBitmapBeans.add(bean);
//
//            if (mSelectImgTotalNum == 1) {
//                if (isPickToFreeStyle() || isAddImage4Freestyle() || isPickToCollageMode4Template()) {
//                    mSelectTip.setText(getString(R.string.select_photo_one, mSelectImgTotalNum, mCollageBitmapBeans.size()));
//                } else {
//                    mSelectTip.setText(getString(R.string.select_photo_video_one, mSelectImgTotalNum, mCollageBitmapBeans.size()));
//                }
//            } else {
//                if (isPickToFreeStyle() || isAddImage4Freestyle() || isPickToCollageMode4Template()) {
//                    mSelectTip.setText(getString(R.string.select_photos, mSelectImgTotalNum, mCollageBitmapBeans.size()));
//                } else {
//                    mSelectTip.setText(getString(R.string.select_photos_videos, mSelectImgTotalNum, mCollageBitmapBeans.size()));
//                    if (thumbnailBean.getDuration() > MAX_DURATION_VIDEO
//                            && SPDataManager.needShowByond30sVideoTip()) {
//                        // 选中超过30s视频，第一次弹窗提示：超过30s视频在collage时会被裁剪成30s
//                        SPDataManager.setShowByond30sVideoTip(false);
//                        showSelBeyond30sVideoDialog(this, null);
//                    }
//                }
//            }
//            RelativeLayout relativeLayout = new RelativeLayout(this);
//            if(mSelectBeanList == null){
//                mSelectBeanList = new ArrayList<>();
//            }
//            SelectBean selectBean = new SelectBean(bean, thumbnailBean, type);
//            mSelectBeanList.add(selectBean);
//            relativeLayout.setTag(selectBean);
//
//            int size = getResources().getDimensionPixelSize(R.dimen.gallery_select_bitmap_size);
//            int closeSize = getResources().getDimensionPixelSize(R.dimen.gallery_select_close_size);
//            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(size, size);
//            ImageView imageView = new ImageView(this);
//            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//            lp.topMargin = closeSize / 2;
//            lp.leftMargin = closeSize / 2;
//            relativeLayout.addView(imageView, lp);
////            FetcherHolder.getSmallImageFetcher().loadImage(bean.mPath, bean.mDegree, imageView, true);
//            if (thumbnail == null) {
//                ImageLoader.loadImage(this, bean.mUri.toString(), R.drawable.ic_default_image, imageView);
//            } else {
//                imageView.setImageBitmap(thumbnail);
//            }
//            ImageView close = new ImageView(this);
//            close.setTag("close");
//            close.setImageResource(R.drawable.icon_collage_select_cancle);
//            RelativeLayout.LayoutParams closelp = new RelativeLayout.LayoutParams(closeSize, closeSize);
//            closelp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
//            closelp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
//            relativeLayout.addView(close, closelp);
//
//            View.OnClickListener onClickListener = new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    RelativeLayout layout = (RelativeLayout)(v.getParent());
//                    SelectBean bean = (SelectBean) layout.getTag();
//                    mCollageBitmapBeans.remove(bean.mBitmapBean);
//                    mScrollLayout.removeView(layout);
//                    if (mSelectImgTotalNum == 1) {
//                        if (isPickToFreeStyle() || isAddImage4Freestyle() || isPickToCollageMode4Template()) {
//                            mSelectTip.setText(getString(R.string.select_photo_one, mSelectImgTotalNum, mCollageBitmapBeans.size()));
//                        } else{
//                            mSelectTip.setText(getString(R.string.select_photo_video_one, mSelectImgTotalNum, mCollageBitmapBeans.size()));
//                        }
//                    } else {
//                        if (isPickToFreeStyle() || isAddImage4Freestyle() || isPickToCollageMode4Template()) {
//                            mSelectTip.setText(getString(R.string.select_photos, mSelectImgTotalNum, mCollageBitmapBeans.size()));
//                        } else{
//                            mSelectTip.setText(getString(R.string.select_photos_videos, mSelectImgTotalNum, mCollageBitmapBeans.size()));
//                        }
//                    }
//                    if(mCollageBitmapBeans.size() < 2 && mBtnDeleteAll.getVisibility() == View.VISIBLE){
//                        mBtnDeleteAll.setVisibility(View.GONE);;
//                    }
//                    bean.mThumbnailBean.setSelectCount(bean.mThumbnailBean.getSelectCount() - 1);
//                    mFragments.get(bean.mType).getAdapter().notifyDataSetChanged();
//                }
//            };
//            imageView.setOnClickListener(onClickListener);
//            close.setOnClickListener(onClickListener);
//
//            int layoutWidth = getResources().getDimensionPixelSize(R.dimen.gallery_select_layout_width);
//            int layoutHeight = getResources().getDimensionPixelSize(R.dimen.gallery_select_layout_height);
//            LinearLayout.LayoutParams layoutLp = new LinearLayout.LayoutParams(layoutWidth, layoutHeight);
//            mScrollLayout.addView(relativeLayout, layoutLp);
//            mScrollLayout.post(new Runnable() {
//                @Override
//                public void run() {
//                    mScrollView.fullScroll(View.FOCUS_RIGHT);
//                }
//            });
//            if(mCollageBitmapBeans.size() >= 2 && mBtnDeleteAll.getVisibility() != View.VISIBLE){
//                mBtnDeleteAll.setVisibility(View.VISIBLE);;
//            }
//        }
//    }

    public static void showSelBeyond30sVideoDialog(Context context, final DialogInterface.OnClickListener listener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setPositiveButton(R.string.check_gif_to_video_sure, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (listener != null) {
                    listener.onClick(dialog, which);
                }
                dialog.dismiss();
            }
        });
        builder.setTitle(R.string.tip);

        Drawable drawable = ComponentContext.getContext().getResources().getDrawable(R.drawable.ic_update_emoji1);
        int w = com.common.base.utils.DeviceUtils.dip2px(18);
        int h = com.common.base.utils.DeviceUtils.dip2px(15);
        drawable.setBounds(0, 0, w, h);
        //居中对齐imageSpan
        CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable);
        imageSpan.setYOffset(0);
        String str = ComponentContext.getContext().getResources().getString(R.string.sel_beyond_30s_video_dialog_msg);
        SpannableString sp = new SpannableString(str);
        int start = str.indexOf("1");
        sp.setSpan(imageSpan, start, start + 1, ImageSpan.ALIGN_BASELINE);

        builder.setMessage(sp);

        AlertDialog dialog = builder.create();
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        FontUtil.setAlertDialogCustomFont(dialog);
        dialog.show();
    }

    public boolean canSelect(int type) {
        boolean canSelect = true;
        if (mCollageBitmapBeans.size() >= mSelectImgTotalNum) {
            canSelect = false;
            if (mSelectImgTotalNum == 1) {
                if (isPickToCollageMode()) {
                    ToastUtil.showToast(getString(R.string.already_select_photos_videos, mSelectImgTotalNum));
                } else {
                    ToastUtil.showToast(getString(R.string.already_select_photo_video_one, mSelectImgTotalNum));
                }
            } else {
                if (isPickToCollageMode()) {
                    ToastUtil.showToast(getString(R.string.already_select_photos, mSelectImgTotalNum));
                } else {
                    ToastUtil.showToast(getString(R.string.already_select_photo_one, mSelectImgTotalNum));
                }
            }
        } else if ((type == MediaTypeUtil.TYPE_GIF || type == MediaTypeUtil.TYPE_VIDEO) && getSelectVideoCount() >= mSelectVideoTotalNum) {
            canSelect = false;
            ToastUtil.showToast(getString(R.string.collage_video_max_tip, mSelectVideoTotalNum));
        }
        return canSelect;
    }

    public int getSelectVideoCount() {
        int count = 0;
        for (BitmapBean bean : mCollageBitmapBeans) {
            if (bean.mType == MediaTypeUtil.TYPE_VIDEO || bean.mType == MediaTypeUtil.TYPE_GIF) {
                count++;
            }
        }
        return count;
    }

    class SelectBean {
        BitmapBean mBitmapBean;
        ThumbnailBean mThumbnailBean;
        int mType;

        public SelectBean(BitmapBean bitmapBean, ThumbnailBean thumbnailBean, int type) {
            mBitmapBean = bitmapBean;
            mThumbnailBean = thumbnailBean;
            mType = type;
        }
    }

    @Override
    public void finish() {
        super.finish();
    }

    public String getStickerPkgName() {
        return mStickerPkgName;
    }

    public String getGifTitle() {
        return mGifTitle;
    }

    public int getAutoScrollPosition() {
        return mAutoScrollPosition;
    }

    public String getFilterPkgName() {
        return mFilterPkgName;
    }

    public String getFilerCategoryId() {
        return mFilerCategoryId;
    }

    public String getTemplatePkgName() {
        return mTemplatePkgName;
    }

    private ShowBigImageUtils mAnimationUtils;

    public void showImageView(ViewGroup parentView, GalleryRowItem item, ThumbnailBean bean, RectF startRectF, Bitmap bitmap) {
        if (bitmap == null) {
            return;
        }
        if (mAnimationUtils == null) {
            mAnimationUtils = new ShowBigImageUtils();
        }
        ViewParent parent = item.getParent();//设置这个的原因是  防止出现图片后滑动时parent拦截事件
        if (null != parent)
            parent.requestDisallowInterceptTouchEvent(true);
        mViewPager.setCanScroll(false);//设置这个的原因是  防止出现图片后滑动ViewPager拦截事件
//		View pView = ((View)mViewPager.getParent());
        mAnimationUtils.showImageView(this, parentView, item, bean, startRectF, bitmap,
                null, false);
    }

    public void hideImageView(GalleryRowItem item) {
        ViewParent parent = item.getParent();//设置这个的原因是  图片隐藏后让parent拦截事件
        if (null != parent)
            parent.requestDisallowInterceptTouchEvent(false);
        mViewPager.setCanScroll(true);//隐藏后让ViewPager拦截事件
        if (mAnimationUtils != null) {
            mAnimationUtils.hideImageView();
        }
    }

    public String getMainButtonEntrance() {
        return mMainButtonEntrance;
    }

    public void statisticsBack() {
        statisticsMainBtnAlbumBack();
        //通知栏更新
        NotifyStoreUpdateStatisticUtil.clear();
    }

    public void statisticsMainBtnAlbumBack() {
        if (!TextUtils.isEmpty(mMainButtonEntrance)) {
            StatisticsUtils.statisticsMainBtnAlbumBack(mMainButtonEntrance);
        }
    }

    public void statisticsMainBtnAlbumStart() {
        if (!TextUtils.isEmpty(mMainButtonEntrance)) {
//            StatisticsUtils.statisticsMainBtnAlbumStart(mMainButtonEntrance);
            switch (mMainButtonEntrance) {
                case StatisticsConstant.MAIN_BTN_EFFECT:

                    break;
                case StatisticsConstant.MAIN_BTN_EDIT:

                    break;
                case StatisticsConstant.MAIN_BTN_ADJUST:

                    break;
            }
        }
    }

    public void handlePermission() {
        boolean needRequest = PermissionUtil.needRequestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!needRequest) {
            return;
        }
        StatisticsUtils.statisicsCustomFunction(StatisticsConstant.PERMISSION_GALLERY,
                StatisticsConstant.PERMISSION_GALLERY_KEY_STORAGE_SHOW, String.valueOf(true));
        boolean result = PermissionUtil.requestPermission(GalleryActivity.this,
                PermissionUtil.PERMISSION_REQ_CODE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        mReqPermissionFromSetting = !result;
        if (mReqPermissionFromSetting) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
//                    ToastUtil.showToast(String.format(getString(R.string.permission_storage_error),
//                            getString(R.string.app_name)));
                }
            }, 500);
        }
    }

    /**
     * 复制图片以达到模板支持数量
     */
    private void copyImage() {
        if (mImageList == null) {
            mImageList = new ArrayList<>(mTemplateSupportImgNum);
            mImageList.addAll(mCollageBitmapBeans);
        }
        for (int i = 0; i < mTemplateSupportImgNum - mCollageBitmapBeans.size(); i++) {
            if (i < mCollageBitmapBeans.size()) {
                mImageList.add(mCollageBitmapBeans.get(i));
            }
        }
        if (mImageList.size() < mTemplateSupportImgNum) {
            copyImage();
        }
    }

    public boolean isEnterArtistFilter() {
        return mIsEnterArtistFilter;
    }

}
